package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.commen.Result;
import com.itheima.entiry.*;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private AddressBookService addressBookService;


    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public Result add(@RequestBody Orders orders,HttpSession session){

        Long userId = (Long) session.getAttribute("user");
        orders.setUserId(userId);
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getId,orders.getAddressBookId());
        AddressBook addressBook = addressBookService.getOne(qw);
        String phone = addressBook.getPhone();
        String address = addressBook.getDetail();
        String consignee = addressBook.getConsignee();
        orders.setConsignee(consignee);
        orders.setAddress(address);
        orders.setPhone(phone);
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        BigDecimal AllPrice=new BigDecimal(0);
//        BigDecimal AllNumber=new BigDecimal(0);
        String random = UUID.randomUUID().toString();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal amount = shoppingCart.getAmount();
            AllPrice=AllPrice.add(amount);
//            BigDecimal number = BigDecimal.valueOf(shoppingCart.getNumber());
//            AllNumber=AllNumber.add(number);
        }
//        orders.setNumber(AllNumber.toString());
        orders.setNumber(random);
        orders.setStatus(1);
        orders.setAmount(AllPrice);
        ordersService.save(orders);
        Long ordersId = orders.getId();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            //订单明细
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(ordersId);
            orderDetailService.save(orderDetail);
        }
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        return new Result(1);
    }

    @GetMapping("/userPage")
    public Result page(Integer page,Integer pageSize,HttpSession session){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,userId);
        Page<Orders> orders = ordersService.page(ordersPage, qw);
        return new Result(1,orders,null);
    }

    @GetMapping("/page")
    public Result allPage(Integer page, Integer pageSize,
                          Long number, Date beginTime,Date endTime){
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        qw.eq(number!=null,Orders::getNumber,number);
        Page<Orders> ordersPage1 = ordersService.page(ordersPage, qw);
        return new Result(1,ordersPage1);
    }

    @GetMapping("/export")
    public Result export(String beginTime, String endTime, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//        String fileName= URLEncoder.encode("测试","UTF-8").replaceAll("\\+","%20");
        String fileName=UUID.randomUUID().toString();
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");

        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.between(!StringUtils.isEmpty(beginTime) &&!StringUtils.isEmpty(endTime),Orders::getOrderTime,beginTime,endTime);
        List<Orders> list = ordersService.list(qw);
        EasyExcel.write(response.getOutputStream(),Orders.class).sheet("模板").doWrite(list);

        return new Result(1);
    }
}
